<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {

	function __construct() {
		parent::__construct();
	}
	
	public function index()
	{
		if($this->LoggedIn()){
			$this->load->model('offer_model');
			$this->load->model('request_model');
			$data['offers'] = $this->offer_model->get_offers_by_fb_id($this->fb_id);
			$data['requests'] = $this->request_model->get_requests_by_fb_id($this->fb_id);
			$data['latest'] = $this->offer_model->get_latest_offers(LATEST_OFFERS);
		
			$data['title'] = 'Home';
			$data['content_view'] = 'home_view';
			$data['stylesheets'] = array();
			$data['javascripts'] = array();
			$this->load_view($data, TRUE);
		}
	}
	
	//Load the facebook registration page
	function register() {
		$data['title'] = 'Register';
		$data['content_view'] = 'register_view';
		$data['stylesheets'] = array();
		$data['javascripts'] = array();
		$this->load_view($data, FALSE);
	}
	
	
	
	
	//Registers the user into the database
	function register_user() {
		if ($_REQUEST && !$this->fb_cookie) {
			//To extract the user's details
			$response = $this->parse_signed_request($_REQUEST['signed_request'], $this->config->item('fb_secret'));
       		
			$this->load->model('User_model');
			$query = $this->User_model->insert_user($response);
			
			// saves Facebook User ID
			$this->fb_id = $response['user_id'];
			
			redirect(site_url());
		}
	}
	
	//For use of facebook registration
	private function parse_signed_request($signed_request, $secret) {
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

		// decode the data
		$sig = $this->base64_url_decode($encoded_sig);
		$data = json_decode($this->base64_url_decode($payload), true);

		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
			error_log('Unknown algorithm. Expected HMAC-SHA256');
			return null;
		}

		// check sig
		$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
		if ($sig !== $expected_sig) {
			error_log('Bad Signed JSON signature!');
			return null;
		}

		return $data;
	}
	
	//For use of facebook registration
	private function base64_url_decode($input) {
		return base64_decode(strtr($input, '-_', '+/'));
	}
}
